/**
 * All rights Reserved, Designed By junglead.cn
 * @package cn.junglead.common.mfa
 * @title GoogleAuthUtil.java
 * @date 2020年12月10日
 */
package cn.junglead.common.mfa;

import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator;

/**
 * 两步验证的操作类，生成普通的两步验证对象
 * @author Gary.Wang
 * @version 1.0
 */
public final class GoogleAuthUtil {
	/**
	 * private 1:生成简单的验证器
	 * @return 返回验证器对象
	 */
	private static GoogleAuthenticator generatorSimpleGoogleAuthenticator() {
		return new GoogleAuthenticator();
	}
	
	/**
	 * 1 生成身份票据
	 * @return 返回生成的票据
	 */
	public static GoogleAuthenticatorKey generatorSecretKey() {
		GoogleAuthenticator ga = generatorSimpleGoogleAuthenticator();
		return ga.createCredentials();
	}
	
	/**
	 * 2 返回组装的url对象
	 * @param issuer 发卡机构名称
	 * @param accountName 账户名
	 * @param credentials 身份凭据
	 * @return 返回校验结果
	 */
	public static String generatorOtpAuthUrl(String issuer, String accountName, GoogleAuthenticatorKey credentials) {
		return GoogleAuthenticatorQRGenerator.getOtpAuthURL(issuer, accountName, credentials);
	}
	
	/**
	 * 3 返回totp协议
	 * @param issuer 发卡机构名称
	 * @param accountName 账户名
	 * @param credentials 身份凭据
	 * @return 返回校验结果
	 */
	public static String generatorOtpAuthTotpURL(String issuer, String accountName, GoogleAuthenticatorKey credentials) {
		return GoogleAuthenticatorQRGenerator.getOtpAuthTotpURL(issuer, accountName, credentials);
	}
	
	/**
	 * 3 生成密码
	 * @param secretKey 秘钥文本
	 * @return 返回生成的密码
	 */
	public static int generatorPassword(String secretKey) {
		GoogleAuthenticator ga = generatorSimpleGoogleAuthenticator();
		return ga.getTotpPassword(secretKey);
	}
	
	/**
	 * 4 验证秘钥
	 * @param secretKey 安全秘钥
	 * @param password 密文
	 * @return 返回校验结果
	 */
	public static boolean verifyPassword(String secretKey, int password) {
		GoogleAuthenticator ga = generatorSimpleGoogleAuthenticator();
		return ga.authorize(secretKey, password);
	}
}
